package com.lsl.controller;

import com.lsl.entity.User;
import com.lsl.entity.Result;
import com.lsl.service.UserService;
import com.lsl.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user-service")
public class LoginController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result<String> login(@RequestBody User user) {
        try {
            User dbUser = userService.getById(user.getId());
            if (dbUser == null || !dbUser.getPassword().equals(user.getPassword())) {
                return Result.error(401, "ID或密码错误");
            }
            String token = JwtUtil.generateToken(String.valueOf(dbUser.getId()));
            return Result.success(token);
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    @GetMapping("/findUser")
    public Result<User> findUser(@RequestHeader("Authorization") String token) {
        try {
            String userId = JwtUtil.getUserIdFromToken(token.replace("Bearer ", ""));
            User user = userService.getById(userId);
            return Result.success(user);
        } catch (Exception e) {
            return Result.error(401, "无效的token");
        }
    }

    @PostMapping("/signup")
    public Result<User> signup(@RequestBody User user) {
        try {
            // 检查用户名是否已存在
            if (userService.lambdaQuery()
                    .eq(User::getUsername, user.getUsername())
                    .exists()) {
                return Result.error(400, "用户名已存在");
            }
            // 检查手机号码是否已存在（防止手机号码重复注册）
            if (userService.lambdaQuery()
                    .eq(User::getPhone, user.getPhone())
                    .exists()) {
                return Result.error(400, "该手机号码已存在一个账号");
            }
            // 保存用户
            userService.save(user);
            // 从数据库重新查询该用户（通过手机号码）
            User dbUser = userService.lambdaQuery()
                    .eq(User::getPhone, user.getPhone())
                    .one();
            return Result.success(dbUser);
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }
}